//
//  AudioTransition.m
//  Recorder
//
//  Created by chenTengfei on 15/1/30.
//  Copyright (c) 2015年 chenTengfei. All rights reserved.
//

#import "AudioTransition.h"

@implementation AudioTransition

+ (AudioTransition *)sharedInstance
{
    static AudioTransition *sharObject;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharObject = [[AudioTransition alloc] init];
    });
    return sharObject;
}

/**
 *  将CAF音频转换为MP3格式
 *
 *  @param cafPath caf文件路径
 *  @param mp3Path MP3文件路径
 *
 *  @return 转换成功YES
 */
- (BOOL)MP3withCafPath:(NSString *)cafFilePath mp3Path:(NSString *)mp3FilePath
{
    
    BOOL result = YES;
    
    NSLog(@"--mp3路径: %@", mp3FilePath);
    
    NSFileManager* fileManager=[NSFileManager defaultManager];
    if([fileManager removeItemAtPath:mp3FilePath error:nil])
    {
        NSLog(@"删除");
    }
    
    @try {
        int read, write;
        
        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置
        if (pcm != NULL) {
            fseek(pcm, 4*1024, SEEK_CUR);  
        }
                                         //skip file header
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output 输出生成的Mp3文件位置
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 11025.0);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            if (pcm != NULL) {
                read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            }
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"---转换错误:%@",[exception description]);
        result = NO;
    }
    @finally {
        
    }
    
    return result;
}
@end
